package com.zimin.cloud.gateway.filter;

import com.zimin.cloud.gateway.constant.GatewayConstant;
import com.zimin.cloud.mine.pojo.system.view.AccountVO;
import com.zimin.common.constant.ServletConstant;
import com.zimin.common.exception.GraceException;
import com.zimin.common.utils.ServletUtil;
import com.zimin.redis.constant.authorize.AuthorizeRedisConstant;
import com.zimin.redis.utils.RedisOperator;
import com.zimin.shared.enums.ResponseStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>全局过滤器，给非登录请求添加请求头</p>
 *
 * @author zimin
 * @since 2021/11/1 3:10 下午
 */
@Component
public class AuthorizeGlobalFilter implements GlobalFilter {

    @Autowired
    private RedisOperator redisOperator;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        var url = exchange.getRequest().getURI().getPath();
        //TODO:黑名单
        //TODO:白名单
        if (!GatewayConstant.LOGIN_SET.contains(url)) {
            var token = ServletUtil.getToken(exchange.getRequest());
            var accountVO = redisOperator.get(String.format(AuthorizeRedisConstant.REDIS_LOGIN_INFO, token), AccountVO.class);
            GraceException.isNull(accountVO, ResponseStatusEnum.TOKEN_EXPIRES);
            ServerHttpRequest mutableReq = null;
            try {
                mutableReq = exchange.getRequest().mutate()
                        .header(ServletConstant.USER_ID, accountVO.getId())
                        .header(ServletConstant.USER_NAME, accountVO.getAccountName())
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }
            var mutableExchange = exchange.mutate().request(mutableReq).build();
            return chain.filter(mutableExchange);
        }
        return chain.filter(exchange);
    }
}
